package com.etoak.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.etoak.common.core.constant.CommonConstant;
import com.etoak.common.core.vo.ResultVO;
import com.etoak.common.redis.RedisService;
import com.etoak.vo.CodeVO;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/code")
public class CodeController {

    @Autowired
    DefaultKaptcha kaptcha;

    @Autowired
    private RedisService redisService;


    @GetMapping("/getCode")
    public ResultVO<CodeVO> getCode() throws IOException {
        String text = kaptcha.createText();
        String[] textArray = text.split(StrUtil.AT);

        //保存验证码值到redis
        String uuid = IdUtil.simpleUUID();
        String redisKey = CommonConstant.KAPTCHA_PREFIX + uuid;
        redisService.setex(redisKey,textArray[1],5, TimeUnit.MINUTES);

        BufferedImage image = kaptcha.createImage(textArray[0]);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image,"png",outputStream);

        String base64 = Base64.encode(outputStream.toByteArray());
        CodeVO codeVO = new CodeVO(uuid, "data:image/png;base64," + base64);

        return ResultVO.success(codeVO);
    }
}
